package com.ourhealth.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ourhealth.constant.MessageConstant;
import com.ourhealth.constant.RedisMessageConstant;
import com.ourhealth.entity.Result;
import com.ourhealth.pojo.Member;
import com.ourhealth.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private LoginService loginService;
    @RequestMapping("check")
    public Result check(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode= (String)map.get("validateCode");
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (!code.equals(validateCode)){
            return new Result(false, "验证码错误");
        }
        Member memberByTelephone = loginService.findMemberByTelephone(telephone);
        if (memberByTelephone==null){
            memberByTelephone = new Member();
            memberByTelephone.setRegTime(new Date());
            memberByTelephone.setPhoneNumber(telephone);
            loginService.addMember(memberByTelephone);
        }
        String token = UUID.randomUUID().toString();
        Jedis resource = jedisPool.getResource();
        resource.setex(token,50*60, JSON.toJSONString(memberByTelephone));
        resource.close();
        return new Result(true, MessageConstant.LOGIN_SUCCESS,token);
    }
}
